#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
import os
import threading
import logging
import re
import asyncio
from datetime import datetime
import db

import settings
from logger import set_logger


def getblogs(page=None, path='/root'):
    page = page if page is not None and isinstance(
        page, dict) else {'index': 1, 'size': 5}
    try:
        session = db.create_session()
        index = int(page.get('index', 1))
        size = int(page.get('size', 5))
        blogs = [item.dobule_to_dict() for item in session.query(db.Blog).filter_by(
            path=path).order_by(db.Blog.created_at.desc()).offset((index - 1) * size).limit(size)]
        total = len([item for item in session.query(
            db.Blog).filter_by(path=path)])
        total_page = (total - 1) // size + 1
        pre = False if index == 1 else True
        next_ = index < total_page
        page = {
            'index': index,
            'total': total,
            'total_page': total_page,
            'pre': pre, 'next': next_
        }
    except BaseException as e:
        logging.error(e)
        page = {
            'index': 1,
            'total': 0,
            'total_page': 0,
            'pre': False, 'next': False
        }
        blogs = []
    return {'blogs': blogs, 'page': page, 'path': path[1:].split('/')}


def get_blog(path):
    try:
        session = db.create_session()
        ppath, pname = path.rsplit('/', 1)
        if len(ppath) <= 0:
            ppath = None
        blogitem = session.query(db.Blog).filter_by(
            path=ppath, name=pname).first()
        if blogitem.content_type == 'd':
            return {'status': True, 'msg': None}
        else:
            return {'status': True, 'msg': blogitem}
    except BaseException as e:
        return {'status': False, 'msg': e}


def save_blog(data, user_id=None):
    try:
        session = db.create_session()
        ppath, pname = data['path'].rsplit('/', 1)
        if len(ppath) <= 0:
            ppath = None
        else:
            mkdirs(ppath)
        blog = session.query(db.Blog).filter_by(
            path=ppath, name=pname).first()
        if blog and blog != 'd':
            blog.name = data['name']
            blog.summary = data['summary']
            blog.content = data['content']
            blog.updated_at = datetime.now()
            blog.updated_date = blog.updated_at.strftime('%Y%m%d')
            blog.updated_stamp = blog.updated_at.timestamp()
        else:
            blog = db.Blog(path=ppath, name=data['name'], summary=data['summary'],
                           content=data['content'], content_type='hls')
            session.add(blog)
        session.commit()
        blog = session.query(db.Blog).filter_by(
            path=ppath, name=data['name']).first()
        return {'status': True, 'msg': blog}
    except BaseException as e:
        return {'status': False, 'msg': e}


def makedir(parent, name, user_id=None):
    try:
        session = db.create_session()
        ppath, pname = parent.rsplit('/', 1)
        if len([item for item in session.query(db.Blog).filter_by(path=ppath if len(ppath) > 0 else None, name=pname, content_type='d')]) <= 0:
            return {'status': False, 'msg': '文件夹(%s)不存在' % parent}
        if len([item for item in session.query(db.Blog).filter_by(path=parent, name=name, content_type='d')]) > 0:
            return {'status': False, 'msg': '文件夹(%s/%s)已存在' % (parent, name)}
        blog = db.Blog(name=name, path=parent,
                       user_id=user_id, content_type='d')
        session.add(blog)
        session.commit()
        return {'status': True, 'msg': '%s/%s' % (parent, name)}
    except BaseException as e:
        return {'status': False, 'msg': e}


def delete(id, user_id=None):
    try:
        session = db.create_session()
        blog = session.query(db.Blog).filter_by(id=id).first()
        if blog:
            if blog.content_type == 'd':
                session.query(db.Blog).filter(db.Blog.path.like(
                    '%s/%s%%' % (blog.path, blog.name))).delete(synchronize_session=False)
            session.delete(blog)
            session.commit()
            return {'status': True, 'msg': '删除[%s]成功' % id}
        else:
            return {'status': False, 'msg': 'blog[%s]不存在' % id}
    except BaseException as e:
        return {'status': False, 'msg': e}


def blog_export(fullpath):
    try:
        parent, name = fullpath.rsplit('/', 1)
        if len(parent) <= 0:
            parent = None
        session = db.create_session()
        blogitem = session.query(db.Blog).filter_by(
            path=parent, name=name).first()
        if not blogitem:
            return {'status': False, 'msg': '文件[%s/%s]不存在' % (parent, name)}
        # 0: 下载中
        result = []
        if blogitem.content_type == 'd':
            return {'status': False, 'msg': '文件[%s/%s]不是blog文件' % (parent, name)}
        else:
            result.append({'path': blogitem.path, 'name': blogitem.name, 'content_type': 'blog', 'user_id': blogitem.user_id,
                           'summary': blogitem.summary, 'content': blogitem.content})
    except BaseException as e:
        return {'status': False, 'msg': e}
    return {'status': True, 'msg': result}


def mkdirs(fullpath):
    session = db.create_session()
    ppath, pname = fullpath.rsplit('/', 1)
    if len(ppath) > 0:
        hlsitem = session.query(db.Hlsitem).filter_by(
            name=pname, path=ppath).first()
        if hlsitem:
            return
        mkdirs(ppath)
        hlsitem = db.Hlsitem(status=1, name=pname,
                             path=ppath, content_type='d')
        session.add(hlsitem)
        session.commit()
    else:
        parent, name = (None, pname)
        hlsitem = session.query(db.Hlsitem).filter_by(
            name=name, path=parent).first()
        if hlsitem:
            return


def import_data(data):
    additem = []
    try:
        session = db.create_session()
        paths = []
        fileitem_exists = []
        fileitem_not_exists = []
        logging.warning('data: %s' % data)
        for item in data:
            if not 'name' in item or not 'path' in item:
                logging.error('[--]文件[%s/%s]格式不正确: %s' %
                              (item['path'], item['name'], item))
                return {'status': False, 'msg': '[--]文件[%s/%s]格式不正确: %s' % (item['path'], item['name'], item)}
            blogitem = session.query(db.Blog).filter_by(
                name=item['name'], path=item['path']).first()
            if blogitem:
                logging.warning('[-]文件[%s/%s]已存在' %
                                (item['path'], item['name']))
                fileitem_exists.append(item)
            else:
                fileitem_not_exists.append(item)
                if item['path'] in paths:
                    continue
                paths.append(item['path'])
        logging.warning('fileitem_exists: %s' % fileitem_exists)
        logging.warning('fileitem_not_exists: %s' % fileitem_not_exists)
        for path in paths:
            mkdirs(path)

        for item in fileitem_not_exists:
            # -1: 下载已暂停
            blogitem = db.Blog(
                status=-1, name=item['name'], path=item['path'], summary=item['summary'], content=item['content'], user_id=item['user_id'], content_type='blog')
            session.add(blogitem)
            session.commit()
            blogtmp = session.query(db.Blog).filter_by(
                name=item['name'], path=item['path']).first()
            additem.append(blogtmp)
    except BaseException as e:
        return {'status': False, 'msg': e}
    return {'status': True, 'msg': additem}


if '__main__' == __name__:
    print(getblogs())
